<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.leagueName" placeholder="联盟名称" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        筛选
      </el-button>
      <el-button v-waves class="filter-item" icon="el-icon-setting" @click="handlePattern">
        关键词设置
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      max-height="690"
      highlight-current-row
      style="width: 100%;"
      :row-style="{height:'32px'}"
      tooltip-effect="light"
      :default-sort="{prop: 'leagueId', order: null}"
      @sort-change="sortChange"
    >
      <el-table-column label="编号" align="center" fixed width="90px" prop="leagueId" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.leagueId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联盟名称" align="center" min-width="120px">
        <template slot-scope="{row}">
          <span>{{ row.leagueName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联盟头像" align="center" width="100px">
        <template slot-scope="{row}">
          <el-image style="max-width: 50px; max-height: 28px" :src="row.leagueImg" :preview-src-list="[row.leagueImg]" />
        </template>
      </el-table-column>
      <el-table-column label="联盟介绍" align="center" min-width="200px" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.leagueDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加入人数" align="center" prop="population" sortable="custom" width="110px">
        <template slot-scope="{row}">
          <span>{{ row.population }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人ID" align="center" prop="userId" sortable="custom" width="120px">
        <template slot-scope="{row}">
          <span>{{ row.userId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人姓名" align="center" width="130px">
        <template slot-scope="{row}">
          <span>{{ row.realName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否置顶" align="center" prop="leagueTop" sortable="custom" width="110px">
        <template slot-scope="{row}">
          <el-tag v-if="row.leagueTop===1" size="mini" effect="dark" type="success">已置顶</el-tag>
          <el-tag v-else size="mini" effect="dark" type="info">未置顶</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="leagueTop" sortable="custom" width="110px">
        <template slot-scope="{row}">
          <el-tag v-if="row.isPass===0" size="mini" effect="dark" type="primary">待审核</el-tag>
          <el-tag v-else-if="row.isPass===1" size="mini" effect="dark" type="success">通过</el-tag>
          <el-tag v-else size="mini" effect="dark" type="info">不通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="权限范围" align="center" prop="authority" sortable="custom" width="110px">
        <template slot-scope="{row}">
          <el-tag v-if="row.authority===0" size="mini" type="success">无限制</el-tag>
          <el-tag v-else-if="row.authority===1" size="mini" type="primary">仅在职员工</el-tag>
          <el-tag v-else size="mini" type="danger">仅民警</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最近修改时间" align="center" prop="updateTime" sortable="custom" width="140px">
        <template slot-scope="{row}">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="240px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button v-if="row.leagueTop===0" type="text" size="mini" @click="doTop(row.leagueId)">
            置顶
          </el-button>
          <el-button v-if="row.leagueTop===1" type="text" size="mini" @click="cancelTop(row.leagueId)">
            取消置顶
          </el-button>
          <el-button type="text" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="text" size="mini" @click="handleAuthority(row)">
            权限
          </el-button>
          <el-button type="text" size="mini" @click="handlePass(row)">
            审核
          </el-button>
          <el-button type="text" size="mini" @click="handleDelete(row.leagueId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page-num.sync="listQuery.pageNum" :page-size.sync="listQuery.pageSize" @pagination="showLeagueSectionList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogVisible" width="30%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="100px" style="width: 100%">
        <el-form-item label="联盟名称" prop="leagueName">
          <el-input v-model="temp.leagueName" style="width: 90%" />
        </el-form-item>
        <el-form-item label="联盟头像" prop="leagueImg">
          <el-input v-model="temp.leagueImg" placeholder="图片链接" style="width: 90%" />
          <img-upload-single @onUpload="uploadImg" @onRemove="removeImg" ref="imgUpload"></img-upload-single>
        </el-form-item>
        <el-form-item label="联盟简介" prop="leagueDesc">
          <el-input v-model="temp.leagueDesc" type="textarea" :row="3" style="width: 90%" />
        </el-form-item>
        <el-form-item label="是否置顶" prop="leagueTop">
          <el-switch v-model="temp.leagueTop" :active-value="1" :inactive-value="0" active-color="#13ce66"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="审核联盟" :visible.sync="dialogPassVisible" width="500px">
      <el-form ref="passForm" :rules="passRules" :model="tempPass" label-width="130px">
        <el-form-item label="审核结果" prop="isPass">
          <el-radio v-model="tempPass.isPass" :label="1">通过</el-radio>
          <el-radio v-model="tempPass.isPass" :label="2">不通过</el-radio>
        </el-form-item>
        <p style="margin-left: 50px">注：审核通过后，该联盟才能被展示</p>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPassVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="doPass">
          确认审核
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="设置联盟权限" :visible.sync="dialogAuthVisible" width="500px">
      <el-form ref="authForm" :rules="authRules" :model="tempAuth" label-width="130px">
        <el-form-item label="权限范围" prop="authority">
          <el-select v-model="tempAuth.authority" placeholder="请选择">
            <el-option
              v-for="item in authOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAuthVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="setAuthority">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="联盟名称关键词设置" :visible.sync="dialogPatternVisible" width="600px">
      <div>
        <el-tag
          v-for="item in patternList"
          :key="'edit-pattern-'+item.patternId"
          class="old-tag"
          closable
          effect="plain"
          type="primary"
          :disable-transitions="true"
          @close="handleDelPattern(item.patternId)"
        >
          {{ item.patternContent }}
        </el-tag>
        <br>
        <span v-if="patternInputVisible">
          <el-input
            ref="patternInput"
            v-model="tempPattern"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleAddPattern"
          />
          <el-button class="button-new-tag" plain size="small" type="success" @click="handleAddPattern">确认</el-button>
          <el-button class="button-new-tag" plain size="small" @click="exitPatternInput">取消</el-button>
        </span>
        <el-button v-else class="button-new-tag" size="small" @click="showPatternInput">+ 新增</el-button>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPatternVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  showLeagueSectionList,
  deleteLeagueSection,
  saveOrUpdateLeagueSection,
  checkLeagueSection,
  setLeagueSectionAuthority,
  getLeagueNamePatternList,
  deleteLeagueNamePattern,
  addLeagueNamePattern
} from '@/api/discuss'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import ImgUploadSingle from '@/components/ImgUpload/ImgUploadSingle'
import { isInteger } from '@/utils/validate'

export default {
  name: 'LeagueSection',
  components: { Pagination, ImgUploadSingle },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      dialogLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        sortProp: '',
        sortOrder: '',
        leagueName: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      temp: {
        leagueId: undefined,
        leagueName: '',
        leagueImg: '',
        leagueDesc: '',
        leagueTop: 0
      },
      tempPass: {},
      tempAuth: {},
      patternList: [],
      patternInputVisible: false,
      tempPattern: '',
      rules: {
        leagueName: [{ required: true, message: '请填写联盟名称', trigger: 'change' }],
        leagueTop: [{ required: true, message: '请设置是否置顶', trigger: 'change' }],
        leagueImg: [{ required: true, message: '请上传联盟头像', trigger: 'change' }],
        leagueDesc: [{ required: true, message: '请设置联盟简介', trigger: 'change' }]
      },
      passRules: {
        isPass: [{ required: true, message: '请选择审核结果', trigger: 'change' }, { validator: isInteger, trigger: 'blur' }]
      },
      authRules: {
        authority: [{ required: true, message: '请选择权限范围', trigger: 'change' }]
      },
      dialogVisible: false,
      dialogPassVisible: false,
      dialogAuthVisible: false,
      dialogPatternVisible: false,
      authOptions: [
        { value: 0, label: '无限制' },
        { value: 1, label: '在职员工可见' },
        { value: 2, label: '仅民警可见' }
      ]
    }
  },
  created() {
    this.showLeagueSectionList()
  },
  methods: {
    showLeagueSectionList() {
      this.listLoading = true
      showLeagueSectionList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.showLeagueSectionList()
    },
    sortChange(data) {
      const { prop, order } = data
      this.listQuery.sortProp = prop
      if (order === 'ascending') {
        this.listQuery.sortOrder = '1'
      } else {
        this.listQuery.sortOrder = '-1'
      }
      this.handleFilter()
    },
    resetDialog() {
      this.temp = {
        leagueId: undefined,
        leagueName: '',
        leagueTop: 0
      }
    },
    handleCreate() {
      this.resetDialog()
      this.dialogStatus = 'create'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveOrUpdateLeagueSection(this.temp).then(() => {
            this.showLeagueSectionList()
            this.dialogVisible = false
            this.$notify({
              title: 'Success',
              message: '新增联盟成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveOrUpdateLeagueSection(this.temp).then(() => {
            this.showLeagueSectionList()
            this.dialogVisible = false
            this.$notify({
              title: 'Success',
              message: '编辑联盟成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    doTop(leagueId) {
      saveOrUpdateLeagueSection({ leagueId: leagueId, leagueTop: 1 }).then(() => {
        this.showLeagueSectionList()
        this.dialogVisible = false
        this.$notify({
          title: 'Success',
          message: '联盟置顶成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    cancelTop(leagueId) {
      saveOrUpdateLeagueSection({ leagueId: leagueId, leagueTop: 0 }).then(() => {
        this.showLeagueSectionList()
        this.dialogVisible = false
        this.$notify({
          title: 'Success',
          message: '联盟取消置顶成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleDelete(bulletinId) {
      this.$confirm('此操作将删除该联盟，该联盟下的帖子将无法展示，是否继续?', '提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteLeagueSection(bulletinId).then(() => {
          this.showLeagueSectionList()
          this.dialogVisible = false
          this.$notify({
            title: 'Success',
            message: '删除联盟成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    handlePass(row) {
      this.tempPass = {
        sectionId: row.leagueId,
        isPass: row.isPass
      }
      this.dialogPassVisible = true
    },
    doPass() {
      this.$refs['passForm'].validate((valid) => {
        if (valid) {
          checkLeagueSection(this.tempPass).then(response => {
            this.showLeagueSectionList()
            this.dialogPassVisible = false
            this.$notify({
              title: 'Success',
              message: '审核成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleAuthority(row) {
      this.tempAuth = {
        sectionId: row.leagueId,
        authority: row.authority
      }
      this.dialogAuthVisible = true
    },
    setAuthority() {
      this.$refs['authForm'].validate((valid) => {
        if (valid) {
          setLeagueSectionAuthority(this.tempAuth).then(response => {
            this.showLeagueSectionList()
            this.dialogAuthVisible = false
            this.$notify({
              title: 'Success',
              message: '设置联盟权限成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handlePattern() {
      this.dialogPatternVisible = true
      this.getPatternList()
    },
    getPatternList() {
      getLeagueNamePatternList(this.tempAuth).then(response => {
        this.patternList = response.data
      })
    },
    handleDelPattern(patternId) {
      this.$confirm('此操作将删除该关键词，是否继续?', '提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteLeagueNamePattern(patternId).then(() => {
          this.$message({ type: 'success', message: '删除成功' })
          this.getPatternList()
        })
      })
    },
    showPatternInput() {
      this.patternInputVisible = true
      this.$nextTick(_ => {
        this.$refs.patternInput.$refs.input.focus()
      })
    },
    exitPatternInput() {
      this.patternInputVisible = false
      this.tempPattern = ''
    },
    handleAddPattern() {
      const name = this.tempPattern
      if (name) {
        addLeagueNamePattern(name).then(() => {
          this.tempPattern = ''
          this.$message({ type: 'success', message: '新增成功' })
          this.getPatternList()
          this.patternInputVisible = false
        })
      } else {
        this.$message({ type: 'warning', message: '请先填写关键词' })
      }
    },
    removeImg() {
      this.temp.leagueImg = ''
    },
    uploadImg() {
      this.temp.leagueImg = this.$refs.imgUpload.url
    }
  }
}
</script>

<style scoped>
  .old-tag {
    vertical-align: top;
    margin-right: 6px;
    margin-bottom: 10px;
  }
  .button-new-tag {
    margin-left: 6px;
  }
  .input-new-tag {
    width: 120px;
    /*margin-left: 6px;*/
    vertical-align: top;
  }
</style>
